# -*- coding: UTF-8 -*-
'''
@Project: stock
@File: RabbitMq.py
@Notes: 
@Author: zhuyoucheng
@Date: 2021/3/31 0031 16:42
'''

import pika
import time


def default_callback(ch, method, properties, body):
    print('--------default--------')
    print(body)

def test_callback(ch, method, properties, body):
    print('--------test---------')
    print(str(body,'utf8'))

def default1_callback(ch, method, properties, body):
    print('--------test---------')
    print(str(body,'utf8'))
    time.sleep(3)


class RabbitMq(object):

    def __init__(self):
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
        self.channel = self.connection.channel()
        pass

    def push(self, queue='default', json=''):
        try:
            self.channel.queue_declare(queue=queue)
            self.channel.basic_publish(exchange='', routing_key=queue, body=json)
            print('-----------json------------')
            print(json)
        except Exception as e:
            print(e)
        finally:
            # 销毁连接
            self.connection.close()
        pass

    def get(self, queue='hello'):
        try:
            if queue == 'default':
                self.channel.basic_consume(on_message_callback=default_callback,queue=queue,auto_ack=True)
            elif queue == 'hello':
                self.channel.basic_consume(on_message_callback=test_callback, queue=queue, auto_ack=True)
            elif queue =='default1':
                self.channel.basic_consume(on_message_callback=default1_callback, queue=queue, auto_ack=True)

            self.channel.start_consuming()
            print(' [*] Waiting for messages. To exit press CTRL+C')
        except Exception as e:
            print(e)
        finally:
            # 销毁连接
            self.connection.close()
















